package com.ironone.mediaplayerdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.ironone.mediaplayerdemo3.R;

public class MainActivity extends Activity {
	public static MediaPlayer mediaPlayer;
	ImageView loading;
	Animation rotation;
	ToggleButton playButton;
	ToggleButton playHDButton;
	TextView textViewLoading;

	boolean isError = false;
	int isError_ErrorCode = 0;
	NotificationManager mNotificationManager;
	BroadcastReceiver br_commonReceiver;
	int timerToStopPlayback = 5000; // In milliseconds. After this time paused player will be reseted.  
	private static Handler handler = new Handler();
	Runnable runnable;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		textViewLoading = (TextView) findViewById(R.id.textViewLoading);
		playButton = (ToggleButton) findViewById(R.id.togglebutton);
		playHDButton = (ToggleButton) findViewById(R.id.togglehdbutton);
		Button nextButton = (Button) findViewById(R.id.next_button);
		loading = (ImageView) findViewById(R.id.loading);

		rotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_button);
		rotation.setRepeatCount(Animation.INFINITE);

		mediaPlayer = MyMediaPlayer.getMediaPlayerInstance();
		mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

		if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.playing ||
				MyMediaPlayer.getMediaPlayerInstance().isPlaying()) {
			playButton.setChecked(true);
		}
		if(MyMediaPlayer.getIsHDOn()){
			playHDButton.setChecked(true);
		}

		Intent serviceIntent = new Intent(getApplicationContext(), MyMediaPlayerService.class);
		startService(serviceIntent);

		mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

			public void onPrepared(MediaPlayer mp) {
				try {
					stopLoading();
					if(MyMediaPlayer.getMediaPlayerStatus() != MediaPlayerStatus.forcePaused){
						textViewLoading.setText("playing...");
						MyMediaPlayer.playMediaPlayer();						
					}
				}catch (Exception e) {
					playButton.setChecked(false);
					MyMediaPlayer.releaseMediaPlayer();
				}
			}
		});

		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer arg0) {
				textViewLoading.setText("on complete");

				if(isError){
					textViewLoading.setText("on complete - error");
					stopLoading();
					MyMediaPlayer.resetMediaPlayer();

					switch(isError_ErrorCode){
					case -1004:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_IO", Toast.LENGTH_LONG).show();
						break;
					case -1007:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_MALFORMED", Toast.LENGTH_LONG).show();
						break;
					case 200:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK", Toast.LENGTH_LONG).show();
						break;
					case 100:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_SERVER_DIED", Toast.LENGTH_LONG).show();
						break;
					case -110:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_TIMED_OUT", Toast.LENGTH_LONG).show();
						break;
					case 1:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_UNKNOWN", Toast.LENGTH_LONG).show();
						break;
					case -1010:
						Toast.makeText(getBaseContext(), "MEDIA_ERROR_UNSUPPORTED", Toast.LENGTH_LONG).show();
						break;
					}
					playButton.setChecked(false);
				}else {
					startLoading();
					MyMediaPlayer.resetAndPrepareMediaPlayer();		
				}
			}
		});

		mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

			@Override
			public void onBufferingUpdate(MediaPlayer arg0, int percent) {
				//textViewLoading.setText(percent + "%");
				if (percent == 100) {
					textViewLoading.setText("buffer 100");
					startLoading();
					MyMediaPlayer.resetAndPrepareMediaPlayer();
				}
			}
		});

		mediaPlayer.setOnInfoListener(new OnInfoListener() {

			@Override
			public boolean onInfo(MediaPlayer mp, int what, int extra) {

				if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START || what == 703) {
					startLoading();
					textViewLoading.setText("bufferring");
					MyMediaPlayer.setMediaPlayerStatus(MediaPlayerStatus.buffering);
				} else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {		
					textViewLoading.setText("playing...");
					stopLoading();
				}else {
					stopLoading();
				}
				return false;
			}
		});

		mediaPlayer.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				isError = true;
				isError_ErrorCode = extra;
				return false;
			}
		});

		nextButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(MainActivity.this, SecondActivity.class);
				startActivity(i);
				overridePendingTransition(R.anim.slide_left_to_middle, R.anim.slide_middle_to_right);
				finish();
			}
		});
	}

	@Override
	protected void onPause() {
		try {
			super.onPause();
			startNotificationOnStatusBar();
			MyMediaPlayer.setIsPlayerOnBackground(true);
			unregisterReceiver(br_commonReceiver);
		} catch (Exception e) {
			//stopLoading();
			//playButton.setChecked(false);
			MyMediaPlayer.releaseMediaPlayer();
		}
	}

	@Override
	protected void onResume() {
		try {
			super.onResume();

			mediaPlayer = MyMediaPlayer.getMediaPlayerInstance();
			MyMediaPlayer.setIsPlayerOnBackground(false);

			rotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_button);
			rotation.setRepeatCount(Animation.INFINITE);

			myMediaPlayerServiceCallbacks();
			stopNotificationOnStatusBar();

			if(MyMediaPlayer.getIsHDOn()){
				playHDButton.setChecked(true);
			}

			if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.buffering) {
				startLoading();
				playButton.setChecked(true);
				textViewLoading.setText("bufferring");
			}

			if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.playing || MyMediaPlayer.getMediaPlayerInstance().isPlaying()) {
				stopLoading();
				playButton.setChecked(true);
				textViewLoading.setText("playing...");
			}

			if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.paused) {
				stopLoading();
				playButton.setChecked(false);
				textViewLoading.setText("paused");
			}

			if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.forcePaused) {
				stopLoading();
				playButton.setChecked(false);
				textViewLoading.setText("forcePaused");
			}

			if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.reseted) {
				stopLoading();
				playButton.setChecked(false);
				textViewLoading.setText("reset");
			}

			if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.released) {
				stopLoading();
				playButton.setChecked(false);
				textViewLoading.setText("released");
			}
		} catch (Exception e) {
			stopLoading();
			playButton.setChecked(false);
			MyMediaPlayer.releaseMediaPlayer();
		}
	}

	/*@Override
	protected void onDestroy() {
		super.onDestroy();
	}*/

	private void stopLoading() {
		loading.clearAnimation();
		loading.setVisibility(View.INVISIBLE);
	}

	private void startLoading() {
		loading.startAnimation(rotation);
		loading.setVisibility(View.VISIBLE);
	}

	public void onToggleClicked(View view) {
		try {
			boolean on = ((ToggleButton) view).isChecked();
			if (on) {
				// Play
				
				Intent intent2 = new Intent(MyMediaPlayer.ACT_NOTIFICATION);
				intent2.putExtra(MyMediaPlayer.VALUE, MyMediaPlayerServiceNotifyStatus.headsetUnmonted.ordinal()); // value == 1
				sendBroadcast(intent2);
				
				if(MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.released || 
						MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.reseted){
					startLoading();
					
					MyMediaPlayer.getMediaPlayerAudioFocus(getApplicationContext());
					
					MyMediaPlayer.prepareMediaPlayer();
					textViewLoading.setText("preparing...");
				}else if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.paused){
					MyMediaPlayer.playMediaPlayer();
					textViewLoading.setText("playing...");
				}else if (MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.forcePaused) {
					startLoading();
					
					MyMediaPlayer.getMediaPlayerAudioFocus(getApplicationContext());
					
					MyMediaPlayer.prepareMediaPlayer();
					textViewLoading.setText("preparing...");
				}
			} else {				
				// Pause
				if(MyMediaPlayer.getMediaPlayerInstance().isPlaying()|| MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.playing){
					MyMediaPlayer.pauseMediaPlayer();
					textViewLoading.setText("paused");
										
					handler.removeCallbacks(runnable);
					timerToStopPlayback(timerToStopPlayback);
					
				}else {
					MyMediaPlayer.resetMediaPlayer();
					MyMediaPlayer.setMediaPlayerStatus(MediaPlayerStatus.forcePaused);
					stopLoading();
					textViewLoading.setText("forcePaused");
				}
			}
		}catch (Exception e) {
			stopLoading();
			playButton.setChecked(false);
			MyMediaPlayer.releaseMediaPlayer();
		}
	}

	
	public void onToggleHDClicked(View view) {
		try {
			boolean on = ((ToggleButton) view).isChecked();
			if (on) {
				MyMediaPlayer.setIsHDOn(true);
				if (MyMediaPlayer.getMediaPlayerInstance().isPlaying() || MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.playing){
					startLoading();
					MyMediaPlayer.resetAndPrepareMediaPlayer();
					textViewLoading.setText("hd preparing");
				}
			}else {
				MyMediaPlayer.setIsHDOn(false);
				if (MyMediaPlayer.getMediaPlayerInstance().isPlaying() || MyMediaPlayer.getMediaPlayerStatus() == MediaPlayerStatus.playing){
					startLoading();
					MyMediaPlayer.resetAndPrepareMediaPlayer();				
					textViewLoading.setText("preparing");
				}
			}
		}catch (Exception e) {
			MyMediaPlayer.setIsHDOn(false);

			stopLoading();
			playHDButton.setChecked(false);
			MyMediaPlayer.releaseMediaPlayer();
		}
	}
	
	private void timerToStopPlayback(int time) {
		//Handler handler = new Handler();
		handler.postDelayed(runnable = new Runnable() {
			@Override
			public void run() {
				if (!MyMediaPlayer.getMediaPlayerInstance().isPlaying() && MyMediaPlayer.getMediaPlayerStatus() != MediaPlayerStatus.playing) {
					MyMediaPlayer.resetMediaPlayer();
					playButton.setChecked(false);
					textViewLoading.setText("resetted");
				}
			}
		}, time);
	}


	private void startNotificationOnStatusBar(){
		// Notification show in status bar
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.icon).setContentTitle("TNL Radio").setContentText("content text");
		mBuilder.setPriority(2);

		// Creates an explicit intent for an Activity in your app
		// Intent resultIntent = new Intent(this, MainActivity.class);
		Intent resultIntent = this.getIntent();
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(MainActivity.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);

		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int mId = 0;
		// mId allows you to update the notification later on.
		mNotificationManager.notify(mId, mBuilder.build());
	}

	private void stopNotificationOnStatusBar(){
		// Notification clear in status bar
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int mId = 0;
		mNotificationManager.cancel(mId);
	}


	private void myMediaPlayerServiceCallbacks() {
		try {
			br_commonReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					int value = intent.getIntExtra(MyMediaPlayer.VALUE, -1);

					switch (value) {
					case 0 : // MyMediaPlayerServiceNotifyStatus.connectivity
						//MyMediaPlayer.resetMediaPlayer();
						textViewLoading.setText("no network");
						playButton.setChecked(false);
						startLoading();
						//MyMediaPlayer.prepareMediaPlayer();
						MyMediaPlayer.resetAndPrepareMediaPlayer();
						break;

					case 1 : // MyMediaPlayerServiceNotifyStatus.headsetunmonted
						if(MyMediaPlayer.getMediaPlayerInstance().isPlaying()){
							playButton.setChecked(false);
							textViewLoading.setText("paused");
							MyMediaPlayer.pauseMediaPlayer();
						}
						break;
					case 3: // MyMediaPlayerServiceNotifyStatus.audioFocusLost
						if(MyMediaPlayer.getMediaPlayerInstance().isPlaying()){
							MyMediaPlayer.pauseMediaPlayer();
							textViewLoading.setText("paused");
							playButton.setChecked(false);
							timerToStopPlayback(timerToStopPlayback);
						}
						break;

					default:
						MyMediaPlayer.resetMediaPlayer();
						textViewLoading.setText("reseted");
						playButton.setChecked(false);
						break;
					}
				}
			};
			registerReceiver(br_commonReceiver, new IntentFilter(MyMediaPlayer.SVC_NOTIFICATION));
		} catch (Exception e) {
			stopLoading();
			playButton.setChecked(false);
			MyMediaPlayer.releaseMediaPlayer();			
		}
	}
}